package com.tttshaoqi.server.controller;

import com.tttshaoqi.common.result.Result;
import com.tttshaoqi.pojo.entity.User;
import com.tttshaoqi.server.service.UserService;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
@Validated
public class AuthController {

    private final UserService userService;

    @PostMapping("/register")
    public Result<Map<String, Object>> register(@RequestBody RegisterRequest req) {
        User user = userService.registerByPassword(req.getUsername(), req.getPhone(), req.getPassword());
        return Result.success(Map.of("userId", user.getId()));
    }

    @PostMapping("/login/password")
    public Result<Map<String, String>> loginByPassword(@RequestBody PasswordLoginRequest req) {
        String token = userService.loginByPassword(req.getAccount(), req.getPassword());
        if(token == null) {
            return Result.error("账号或密码错误");
        }
        return Result.success(Map.of("token", token));
    }

    @Data
    public static class RegisterRequest {
        @NotBlank
        private String username;
        @NotBlank
        private String phone;
        @NotBlank
        private String password;
    }

    @Data
    public static class PasswordLoginRequest {
        @NotBlank
        private String account; // username 或 phone
        @NotBlank
        private String password;
    }

    @Data
    public static class SmsLoginRequest {
        @NotBlank
        private String phone;
        @NotBlank
        private String code;
    }
}



